import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useAppStore } from '@/stores/appStore';
import { Lock, Shield, Key, Eye, EyeOff, Zap } from 'lucide-react';
import { OriginalDataDisplay } from '@/components/ui/OriginalDataDisplay';

export function Stage1SecretInput() {
  const { zkProofData, experienceMode, generateNewProofData } = useAppStore();
  const [inputValue, setInputValue] = useState('');
  const [showSecret, setShowSecret] = useState(false);
  const [isSecured, setIsSecured] = useState(false);
  const [animationStep, setAnimationStep] = useState(0);
  const [isGenerating, setIsGenerating] = useState(false);
  const [hashGenerationStep, setHashGenerationStep] = useState<'idle' | 'hashing' | 'complete' | 'error'>('idle');
  const [generatedHash, setGeneratedHash] = useState<string>('');
  const [isHashGenerating, setIsHashGenerating] = useState(false);
  
  // Get the actual secret from our data
  const actualSecret = zkProofData?.input?.preImage || '888888';
  
  // 当输入改变时，重置哈希状态
  useEffect(() => {
    if (inputValue !== actualSecret) {
      setGeneratedHash('');
      setHashGenerationStep('idle');
    }
  }, [inputValue, actualSecret]);
  
  useEffect(() => {
    // Auto-fill and animate in education mode
    if (experienceMode.id === 'education') {
      const timer = setTimeout(() => {
        setInputValue(actualSecret);
        setAnimationStep(1);
      }, 1000);
      
      return () => clearTimeout(timer);
    }
  }, [actualSecret, experienceMode.id]);
  
  useEffect(() => {
    if (inputValue === actualSecret && animationStep === 1) {
      const timer = setTimeout(() => {
        setIsSecured(true);
        setAnimationStep(2);
      }, 2000);
      
      return () => clearTimeout(timer);
    }
  }, [inputValue, actualSecret, animationStep]);
  
  const handleSecureSecret = async () => {
    console.log('\n=== 🔒 STAGE 1: 开始存储到保险箱 ===');
    console.log('步骤1.1: 检查输入值:', inputValue);
    
    if (!inputValue) {
      console.log('❌ 步骤1.1失败: 输入值为空');
      return;
    }
    
    try {
      // 如果还没有生成哈希，先生成哈希
      if (!generatedHash) {
        console.log('步骤1.2: 检测到未生成哈希，开始生成...');
        await handleGenerateHash();
        console.log('步骤1.2完成: 哈希生成完毕');
      } else {
        console.log('步骤1.2跳过: 哈希已存在:', generatedHash.slice(0, 20) + '...');
      }
      
      // 存储到保险箱，使用当前的数据
      console.log('步骤1.3: 存储数据到保险箱');
      console.log('  - preImage:', inputValue);
      console.log('  - dataHash:', generatedHash.slice(0, 20) + '...');
      
      setIsSecured(true);
      setAnimationStep(2);
      
      console.log('✅ 步骤1.3完成: 数据已存储到保险箱');
      console.log('🔒 Stage1完成: 数据已存储到保险箱，将在后续流程中保持一致');
      console.log('=== 🔒 STAGE 1: 结束 ===\n');
      
    } catch (error) {
      console.error('❌ Stage1失败: 存储失败:', error);
      console.log('=== 🔒 STAGE 1: 异常结束 ===\n');
    }
  };
  
  // 只生成Poseidon哈希，不生成完整证明
  const handleGenerateHash = async () => {
    console.log('\n=== 🔑 STAGE 1: 开始生成Poseidon哈希 ===');
    
    const trimmedInput = String(inputValue).trim();
    console.log('步骤1.1: 检查并清理输入');
    console.log('  - 原始输入:', inputValue);
    console.log('  - 清理后输入:', trimmedInput);
    
    if (!trimmedInput) {
      console.log('❌ 步骤1.1失败: 输入为空');
      console.log('=== 🔑 STAGE 1: 哈希生成异常结束 ===\n');
      return;
    }
    
    setIsHashGenerating(true);
    setHashGenerationStep('hashing');
    console.log('步骤1.2: 设置生成状态为进行中');
    
    try {
      console.log('步骤1.3: 开始调用HashGen计算Poseidon哈希');
      console.log('  - preImage输入:', trimmedInput);
      
      // 使用HashGen.ts计算Poseidon哈希
      const { calculatePoseidonHash } = await import('@/services/HashGen');
      console.log('步骤1.4: HashGen模块加载完成，开始计算...');
      
      const dataHash = await calculatePoseidonHash(trimmedInput);
      
      console.log('✅ 步骤1.4完成: Poseidon哈希计算成功');
      console.log('  - 生成的dataHash:', dataHash);
      console.log('  - 哈希长度:', dataHash.length, '字符');
      
      setGeneratedHash(dataHash);
      setHashGenerationStep('complete');
      console.log('步骤1.5: 哈希结果已保存到本地状态');
      
      // 立即更新store中的数据，确保技术说明显示最新的哈希
      console.log('步骤1.6: 开始更新全局store数据...');
      await generateNewProofData(trimmedInput);
      console.log('✅ 步骤1.6完成: 全局数据更新成功');
      
      console.log('🎉 Stage1哈希生成完成: preImage -> dataHash');
      console.log('=== 🔑 STAGE 1: 哈希生成结束 ===\n');
      
    } catch (error) {
      console.error('❌ Stage1哈希生成失败:', error);
      console.error('  - 错误类型:', error instanceof Error ? error.constructor.name : typeof error);
      console.error('  - 错误消息:', error instanceof Error ? error.message : String(error));
      setHashGenerationStep('error');
      console.log('=== 🔑 STAGE 1: 哈希生成异常结束 ===\n');
      
      // 重置状态以允许重试
      setTimeout(() => {
        setHashGenerationStep('idle');
      }, 2000);
    } finally {
      setIsHashGenerating(false);
    }
  };

  // 生成完整的证明数据
  const handleCustomInput = async () => {
    const trimmedInput = String(inputValue).trim();
    if (!trimmedInput) return;
    
    setIsGenerating(true);
    
    try {
      // 如果还没有生成哈希，先生成哈希
      if (!generatedHash) {
        await handleGenerateHash();
      }
      
      console.log('🔄 开始生成完整证明数据...');
      
      // 生成完整的证明数据
      const success = await generateNewProofData(trimmedInput);
      if (success) {
        setIsSecured(true);
        setAnimationStep(2);
      }
    } catch (error) {
      console.error('证明生成失败:', error);
    } finally {
      setIsGenerating(false);
    }
  };
  
  return (
    <div className="stage-container">
      <div className="max-w-4xl mx-auto">
        {/* Stage title */}
        <motion.div
          initial={{ opacity: 0, y: -50 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8 }}
          className="text-center mb-12"
        >
          <h1 className="text-5xl font-bold gradient-text mb-4">
            🔐 量子保险箱
          </h1>
          <p className="text-xl text-gray-300">
            请将您的秘密数据安全存储到量子保险箱中
          </p>
        </motion.div>
        
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-center">
          {/* Input section */}
          <motion.div
            initial={{ opacity: 0, x: -100 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.4, duration: 0.8 }}
            className="space-y-6"
          >
            <div className="floating-card">
              <h3 className="text-2xl font-semibold text-white mb-6 flex items-center">
                <Key className="mr-3 text-quantum-blue" size={28} />
                输入您的秘密
              </h3>
              
              {/* Secret input */}
              <div className="relative mb-6">
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  秘密数据 (preImage)
                </label>
                <div className="relative">
                  <input
                    type="text"
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    placeholder="请输入您的秘密数字..."
                    className="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-3 text-white placeholder-gray-400 focus:border-quantum-blue focus:outline-none transition-colors"
                  />
                  <button
                    onClick={() => setShowSecret(!showSecret)}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-white transition-colors"
                  >
                    {showSecret ? <EyeOff size={20} /> : <Eye size={20} />}
                  </button>
                </div>
                
                {/* Input validation */}
                {inputValue && (
                  <motion.div
                    initial={{ opacity: 0, scale: 0.8 }}
                    animate={{ opacity: 1, scale: 1 }}
                    className={`mt-2 flex items-center text-sm ${
                      inputValue === actualSecret ? 'text-green-400' : 'text-yellow-400'
                    }`}
                  >
                    <Shield size={16} className="mr-2" />
                    {inputValue === actualSecret 
                      ? '✅ 验证成功！这是演示中的真实数据' 
                      : '⚠️ 这不是演示数据，但您可以继续体验'}
                  </motion.div>
                )}
              </div>
              
              {/* Security features */}
              <div className="space-y-3 mb-6">
                <div className="flex items-center text-sm text-gray-300">
                  <div className="w-2 h-2 bg-green-500 rounded-full mr-3"></div>
                  端到端加密保护
                </div>
                <div className="flex items-center text-sm text-gray-300">
                  <div className="w-2 h-2 bg-green-500 rounded-full mr-3"></div>
                  本地处理，不会传输原始数据
                </div>
                <div className="flex items-center text-sm text-gray-300">
                  <div className="w-2 h-2 bg-green-500 rounded-full mr-3"></div>
                  使用Poseidon哈希单向加密
                </div>
              </div>
              
              {/* Action buttons */}
              <div className="space-y-3">
                <motion.button
                  onClick={handleSecureSecret}
                  disabled={!inputValue || isSecured}
                  whileHover={{ scale: inputValue && !isSecured ? 1.02 : 1 }}
                  whileTap={{ scale: inputValue && !isSecured ? 0.98 : 1 }}
                  className={`w-full py-3 px-6 rounded-lg font-semibold transition-all ${
                    !inputValue 
                      ? 'bg-gray-700 text-gray-500 cursor-not-allowed'
                      : isSecured 
                      ? 'bg-green-600 text-white cursor-default'
                      : 'bg-quantum-blue hover:bg-blue-600 text-white'
                  }`}
                >
                  {isSecured ? '🔒 已安全存储' : '🔐 存储到保险箱'}
                </motion.button>
                
                {/* Poseidon哈希生成按钮 */}
                {inputValue && !generatedHash && (
                  <motion.button
                    onClick={handleGenerateHash}
                    disabled={isHashGenerating}
                    whileHover={{ scale: !isHashGenerating ? 1.02 : 1 }}
                    whileTap={{ scale: !isHashGenerating ? 0.98 : 1 }}
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className={`w-full py-3 px-6 rounded-lg font-semibold transition-all flex items-center justify-center space-x-2 ${
                      isHashGenerating
                        ? 'bg-gray-700 text-gray-500 cursor-not-allowed'
                        : 'bg-quantum-blue hover:bg-blue-600 text-white'
                    }`}
                  >
                    {isHashGenerating ? (
                      <>
                        <motion.div
                          animate={{ rotate: 360 }}
                          transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                          className="w-5 h-5 border-2 border-white border-t-transparent rounded-full"
                        />
                        <span>正在生成Poseidon哈希...</span>
                      </>
                    ) : (
                      <>
                        <Zap size={20} />
                        <span>
                          {hashGenerationStep === 'error' ? '🔄 重新生成哈希' : '🔐 生成Poseidon哈希'}
                        </span>
                      </>
                    )}
                  </motion.button>
                )}

                {/* 生成完整证明按钮 */}
                {generatedHash && !isSecured && (
                  <motion.button
                    onClick={handleCustomInput}
                    disabled={isGenerating}
                    whileHover={{ scale: !isGenerating ? 1.02 : 1 }}
                    whileTap={{ scale: !isGenerating ? 0.98 : 1 }}
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className={`w-full py-3 px-6 rounded-lg font-semibold transition-all flex items-center justify-center space-x-2 ${
                      isGenerating
                        ? 'bg-gray-700 text-gray-500 cursor-not-allowed'
                        : 'bg-proof-purple hover:bg-purple-600 text-white'
                    }`}
                  >
                    {isGenerating ? (
                      <>
                        <motion.div
                          animate={{ rotate: 360 }}
                          transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                          className="w-5 h-5 border-2 border-white border-t-transparent rounded-full"
                        />
                        <span>生成证明数据中...</span>
                      </>
                    ) : (
                      <>
                        <Shield size={20} />
                        <span>🚀 生成零知识证明</span>
                      </>
                    )}
                  </motion.button>
                )}
              </div>
            </div>
            
            {/* Educational info */}
            {experienceMode.showTechDetails && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.8 }}
                className="bg-slate-800/50 rounded-lg p-4 border border-slate-700"
              >
                <h4 className="text-lg font-semibold text-white mb-3">💡 技术说明</h4>
                <div className="space-y-2 text-sm text-gray-300">
                  <p>• <strong>Poseidon哈希：</strong>专为零知识证明优化的哈希函数</p>
                  <p>• <strong>单向性：</strong>从哈希值无法反推出原始数据</p>
                  <p>• <strong>电路友好：</strong>在zk-SNARK电路中计算高效</p>
                  <p>• <strong>输入数据(preImage)：</strong>{inputValue || actualSecret}</p>
                  <p>• <strong>数据哈希(dataHash)：</strong>
                    {generatedHash ? (
                      <span className="text-green-400">
                        {generatedHash.slice(0, 20)}...{generatedHash.slice(-10)} ✅
                      </span>
                    ) : zkProofData?.input?.dataHash ? (
                      <span>
                        {zkProofData.input.dataHash.slice(0, 20)}...{zkProofData.input.dataHash.slice(-10)}
                      </span>
                    ) : (
                      <span className="text-gray-500">等待生成...</span>
                    )}
                  </p>
                  {generatedHash && (
                    <p className="text-green-400">• <strong>状态：</strong>✅ 新的哈希已生成，点击"存储到保险箱"后将应用到整个流程</p>
                  )}
                </div>
              </motion.div>
            )}
          </motion.div>
          
          {/* Vault visualization */}
          <motion.div
            initial={{ opacity: 0, x: 100 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.6, duration: 0.8 }}
            className="relative"
          >
            {/* Quantum vault */}
            <div className="relative w-80 h-80 mx-auto">
              {/* Outer ring */}
              <motion.div
                animate={{ rotate: isSecured ? 0 : 360 }}
                transition={{ duration: 8, repeat: Infinity, ease: "linear" }}
                className="absolute inset-0 border-4 border-quantum-blue rounded-full opacity-30"
              />
              
              {/* Middle ring */}
              <motion.div
                animate={{ rotate: isSecured ? 0 : -360 }}
                transition={{ duration: 6, repeat: Infinity, ease: "linear" }}
                className="absolute inset-8 border-4 border-crypto-green rounded-full opacity-40"
              />
              
              {/* Inner vault */}
              <motion.div
                animate={{ 
                  scale: isSecured ? 1.1 : 1,
                  boxShadow: isSecured 
                    ? ["0 0 20px rgba(59, 130, 246, 0.3)", "0 0 40px rgba(59, 130, 246, 0.6)", "0 0 20px rgba(59, 130, 246, 0.3)"]
                    : "0 0 20px rgba(59, 130, 246, 0.3)"
                }}
                transition={{ duration: 2, repeat: isSecured ? Infinity : 0 }}
                className="absolute inset-16 bg-gradient-to-br from-slate-800 to-slate-900 rounded-full border-4 border-proof-purple flex items-center justify-center"
              >
                <AnimatePresence mode="wait">
                  {!isSecured ? (
                    <motion.div
                      key="open"
                      initial={{ opacity: 0, scale: 0.8 }}
                      animate={{ opacity: 1, scale: 1 }}
                      exit={{ opacity: 0, scale: 0.8 }}
                      className="text-center"
                    >
                      <Lock size={48} className="text-gray-400 mx-auto mb-2" />
                      <p className="text-gray-400 text-sm">等待数据...</p>
                    </motion.div>
                  ) : (
                    <motion.div
                      key="secured"
                      initial={{ opacity: 0, scale: 0.8 }}
                      animate={{ opacity: 1, scale: 1 }}
                      className="text-center"
                    >
                      <motion.div
                        animate={{ rotate: [0, 10, -10, 0] }}
                        transition={{ duration: 0.5, repeat: 2 }}
                      >
                        <Lock size={48} className="text-quantum-blue mx-auto mb-2" />
                      </motion.div>
                      <p className="text-quantum-blue text-sm font-semibold">已加密存储</p>
                    </motion.div>
                  )}
                </AnimatePresence>
              </motion.div>
              
              {/* Data particles */}
              {inputValue && animationStep >= 1 && (
                <>
                  {Array.from({ length: 12 }, (_, i) => (
                    <motion.div
                      key={i}
                      className="absolute w-3 h-3 bg-quantum-blue rounded-full"
                      style={{
                        left: '50%',
                        top: '50%',
                        x: '-50%',
                        y: '-50%',
                      }}
                      animate={{
                        x: [0, Math.cos(i * 30 * Math.PI / 180) * 100],
                        y: [0, Math.sin(i * 30 * Math.PI / 180) * 100],
                        opacity: isSecured ? [1, 0] : [1, 0.3, 1],
                        scale: isSecured ? [1, 0] : [1, 0.8, 1],
                      }}
                      transition={{
                        duration: isSecured ? 1 : 2,
                        delay: i * 0.1,
                        repeat: isSecured ? 0 : Infinity,
                      }}
                    />
                  ))}
                </>
              )}
              
              {/* Success effect */}
              {isSecured && (
                <motion.div
                  initial={{ scale: 0, opacity: 0 }}
                  animate={{ scale: 2, opacity: [0, 1, 0] }}
                  transition={{ duration: 1.5 }}
                  className="absolute inset-0 border-4 border-green-400 rounded-full"
                />
              )}
            </div>
            
            {/* Status indicator */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 1 }}
              className="text-center mt-8"
            >
              <div className={`inline-flex items-center space-x-2 px-4 py-2 rounded-full ${
                isSecured 
                  ? 'bg-green-900/50 border border-green-500 text-green-300'
                  : 'bg-slate-800/50 border border-slate-600 text-gray-300'
              }`}>
                <div className={`w-3 h-3 rounded-full ${
                  isSecured ? 'bg-green-500' : 'bg-gray-500'
                }`} />
                <span className="font-medium">
                  {isSecured ? '量子保险箱已锁定' : '等待安全存储'}
                </span>
              </div>
            </motion.div>
          </motion.div>
        </div>
        
        {/* Original Data Display */}
        {isSecured && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 1 }}
            className="mt-8"
          >
            <OriginalDataDisplay 
              title="已存储的原始数据"
              compact={experienceMode.id === 'quick' || experienceMode.id === 'presentation'}
              showControls={experienceMode.showTechDetails || experienceMode.showCode}
            />
          </motion.div>
        )}

        {/* Progress to next stage */}
        {isSecured && (
          <motion.div
            initial={{ opacity: 0, y: 50 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 1.5 }}
            className="text-center mt-12"
          >
            <div className="floating-card max-w-md mx-auto">
              <h3 className="text-xl font-semibold text-white mb-3">🎉 存储成功！</h3>
              <p className="text-gray-300 mb-4">
                您的秘密已安全存储在量子保险箱中。接下来我们将生成零知识证明。
              </p>
              <motion.div
                className="text-quantum-blue"
                animate={{ y: [0, -10, 0] }}
                transition={{ duration: 2, repeat: Infinity }}
              >
                <span className="text-2xl">⚡</span>
                <p className="font-semibold">准备生成证明...</p>
              </motion.div>
            </div>
          </motion.div>
        )}
      </div>
    </div>
  );
}